package com.example.myapplication;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.os.Bundle;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.LinearLayout;

public class MyScrollView extends LinearLayout {

    private static final String TAG = "MyScrollView";
    public MyScrollView(Context context) {
        super(context);
    }

    public MyScrollView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
       // View.inflate(context,R.layout.activity_my_scroll_view,this);
    }
int oldX,oldY;
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        Log.e(TAG, "onTouchEvent: "+event.getAction() );


            //在按下的时候记录初始的位置
        if (event.getAction() == MotionEvent.ACTION_DOWN){
            oldX = (int) event.getX();
            oldY = (int) event.getY();
        }

        //计算移动的距离，计算偏移量，ScrollTo
        if (event.getAction() == MotionEvent.ACTION_MOVE){
            int currntX = (int) event.getX();
            int currntY = (int) event.getY();
            int deltaX =currntX - oldX;
            int deltaY =currntY - oldY;


         //限定左滑的范围
            int delwidth = getChildAt(1).getWidth();
            if (deltaX<0 && Math.abs(deltaX)  > delwidth){//向左滑动
                deltaX =  -delwidth;
            }
            if (deltaX > 0 && getScaleX() > 0){
                deltaX = 0;
            }
            //向上向下滑动
            if (Math.abs(deltaY)>10){
                deltaX =0;
            }
            scrollTo(-deltaX,0);
        }

          //在松开时，停止移动

        return true;
    }
}
